package cn.xzqwjw.taskmanager.security.handler;

import cn.xzqwjw.taskmanager.domain.pojo.SysAdmin;
import cn.xzqwjw.taskmanager.domain.vo.ResponseVo;
import cn.xzqwjw.taskmanager.service.LogLoginService;
import cn.xzqwjw.taskmanager.utils.JwtUtil;
import cn.xzqwjw.taskmanager.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义管理员登录成功后的输出格式，这里是输出成json
 *
 * @author rush
 */
@Component
public class LoginSuccessAdminHandler implements AuthenticationSuccessHandler {

  private final LogLoginService logLoginService;

  @Autowired
  public LoginSuccessAdminHandler(LogLoginService logLoginService) {
    this.logLoginService = logLoginService;
  }

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    // 到了这个handler，说明登录验证通过了，因此可以得到 sysAdmin 对象
    SysAdmin sysAdmin = (SysAdmin) authentication.getPrincipal();
    // 过期时间24小时*7 （一周）
    Long expiration = 604800L;
    // 生成jwt令牌
    String strJwt = JwtUtil.createJwt(sysAdmin, expiration);
    Map<String, Object> returnMap = new HashMap<>(16);
    // 管理员的id、username、real_name、mobile_phone、avatar_url、
    // 是否启用 is_enabled、账号是否未过期 is_account_non_expired
    // 账号是否未锁定 is_account_non_locked、密码是否未过期 is_credentials_non_expired
    returnMap.put("id", sysAdmin.getId());
    returnMap.put("uuid", sysAdmin.getUuid());
    returnMap.put("Username", sysAdmin.getUsername());
    returnMap.put("RealName", sysAdmin.getRealName());
    returnMap.put("MobilePhone", sysAdmin.getMobilePhone());
    returnMap.put("AvatarUrl", sysAdmin.getAvatarUrl());
    returnMap.put("IsEnabled", sysAdmin.isEnabled());
    returnMap.put("TotalLoginNumber", logLoginService.countTotalLoginNumber(sysAdmin.getId()));
    Map<String, Object> lastLoginInfoMap = logLoginService.getLastLoginInfoByIdAdmin(sysAdmin.getId());
    returnMap.put("LastLoginTime", lastLoginInfoMap.get("dt_login"));
    returnMap.put("LastLoginIpInner", lastLoginInfoMap.get("ip_inner"));
    returnMap.put("LastLoginIpOuter", lastLoginInfoMap.get("ip_outer"));
    returnMap.put("Menu", sysAdmin.getMenu());
    ResponseUtil.writeJsonJwt(response, strJwt, ResponseVo.success(returnMap));
  }

}
